package com.timmy.bluetooth;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.timmy.bluetooth.adapter.MyAdapter;
import com.timmy.bluetooth.scan.DeviceInfo;
import com.timmy.bluetooth.scan.DeviceScan;
import com.timmy.bluetooth.scan.DeviceScanCallback;
import com.timmy.bluetooth.scan.SortComparator;
import com.timmy.bluetooth.connect.BluetoothConnectClientManager;
import com.timmy.bluetooth.connect.IBluetoothConnectListener;
import com.timmy.bluetooth.connect.ILoopTimerListener;
import com.timmy.bluetooth.connect.LoopTimer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private Button mBtn;
    private BluetoothAdapter bluetoothAdapter;
    private DeviceScan mDeviceScanManager;
    private List<DeviceInfo> deviceInfoList;
    private ListView mListView;
    private ProgressDialog progressDialog;
    private BluetoothConnectClientManager mBluetoothClientManager;
    private LoopTimer loopTimer;
    /**
     * 连接计时
     */
    int connectCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        loopTimer = new LoopTimer(timerListener, 1000);

        deviceInfoList = new ArrayList<>();

        initBluetooth();
    }

    private void initView() {

        mBtn = (Button) findViewById(R.id.main_btn);
        mListView = (ListView) findViewById(R.id.main_btn_listview);

        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("logcat", "开始扫描");
                statrtSeach();
            }
        });
        mListView.setOnItemClickListener(this);
        progressDialog = new ProgressDialog(this);

    }

    private void initBluetooth() {

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (bluetoothAdapter == null) {
            Toast.makeText(this, "蓝牙初始化失败", Toast.LENGTH_SHORT).show();
            return;
        } else {
            bluetoothAdapter.enable();      //打开蓝牙
        }
    }

    /**
     * 开始搜索蓝牙设备
     */
    public void statrtSeach() {

        deviceInfoList.clear();

        progressDialog.show();

        mDeviceScanManager = new DeviceScan();

        mDeviceScanManager.ScanInit(this, new DeviceScanCallback() {
            @Override
            public void onScanStart() {

            }

            @Override
            public void onScanEnd() {

                Log.i("搜索结束", "停止搜索,发送完成信息");
                MyAdapter myAdapter = new MyAdapter(MainActivity.this, deviceInfoList);
                mListView.setAdapter(myAdapter);
                progressDialog.dismiss();
            }

            @Override
            public void onDevice(DeviceInfo deviceInfo) {

                if (deviceInfo.getAddress().length() > 11) {
                    deviceInfoList.add(deviceInfo);
                    //按信号强弱对所有蓝牙设备进行排序
                    sort();
                }
            }
        }, 12);

        mDeviceScanManager.startScan();         //开始扫描
    }

    /**
     * 按信息强度给设备排序
     */
    private void sort() {
        Comparator comp = new SortComparator();
        Collections.sort(deviceInfoList, comp);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        closeBluetooth();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeBluetooth();
    }


    /**
     * 关闭蓝牙
     */
    private void closeBluetooth() {
        mDeviceScanManager.cancelScan();
    }

    /**
     * 点击listview 条目,开始进行连接
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(this, deviceInfoList.get(position).getName() + "进行连接中", Toast.LENGTH_SHORT).show();

        //获取正在点击的item条目信息
        //显示dialog 正在连接
        progressDialog.show();

        //获取单例
        mBluetoothClientManager = BluetoothConnectClientManager.getInstance();

        //开启蓝牙连接,使用蓝牙设备地址去连接设备
        mBluetoothClientManager.BleInited(MainActivity.this, deviceInfoList.get(position).getAddress());

        //设置蓝牙连接监听
        mBluetoothClientManager.setOnBluetoothConnectListener(connectListener);

        loopTimer.startTimer();
    }

    IBluetoothConnectListener connectListener = new IBluetoothConnectListener() {
        @Override
        public void onConnect(BluetoothConnectClientManager.ConnectStatus status) {

            if (status == BluetoothConnectClientManager.ConnectStatus.STATUS_OK) {

                loopTimer.stopTimer();

                mListView.setVisibility(View.GONE);

                progressDialog.dismiss();

                //连接成功后跳转到蓝牙信息页面
                Intent intent = new Intent(MainActivity.this, InfoActivity.class);
                MainActivity.this.startActivity(intent);
                MainActivity.this.finish();
            }
        }

        @Override
        public void onTimer1s() {
        }
    };

    ILoopTimerListener timerListener = new ILoopTimerListener() {
        @Override
        public void onLoopTimer() {
            connectCount++;

            Log.i("连接中", "onLoopTimer: " + connectCount);
            if (connectCount == 40 | MainActivity.this.isFinishing()) {

                connectCount = 0;

                loopTimer.stopTimer();
                mBluetoothClientManager.stopBleConnect();           //停止连接

                Log.i("连接失败了", "onLoopTimer: 连接失败了");
                progressDialog.dismiss();
            }
        }
    };
}
